#!/usr/bin/env python3
import argparse
import itertools
from multiprocessing import Pool

import ujson

from stethistics.checks.verbose import raw_ip_aliases_check, raw_subnet_check, raw_concentration_check


def cc(a):
    d, ps = a
    res = raw_concentration_check(d, ps)['results']
    return ps, (
        sum((v["count"] for v in res)), len(res),
        round(sum((v["count"] for v in res)) / len(res), 2) if len(res) > 0 else None)


cc.header = "threshold;ids_count;groups_count;avg"


def sc(a):
    d, t = a
    return t, (len(raw_subnet_check(d, t)['results']),)


def ac(a):
    d, t = a
    return t, (len(raw_ip_aliases_check(d, t)['results']),)


if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='Ethereum network deviant nodes finder')
    parser.add_argument("infile", help="input json file path", type=argparse.FileType('r', encoding='UTF-8'))
    args = parser.parse_args()
    if args.infile is not None:
        data = ujson.load(args.infile)
        args.infile.close()
        for i, (name, func) in enumerate((("groups", cc), ("subnets", sc), ("aliases", ac))):
            with Pool() as p:
                print(f"{i + 1}/3")
                with open(f"{name}.csv", "w") as file:
                    file.write("threshold;results\n" if not hasattr(func, "header") else func.header + "\n")
                    for j, v in itertools.takewhile(lambda x: x[1][0] > 0,
                                                    p.imap(func, ((data, i) for i in itertools.count()))):
                        file.write(f"{j};{';'.join((str(w) for w in v))}\n")
        else:
            print("Finished !")
